const mysql = require('mysql2/promise');
// require('dotenv').config(); // 已在index.js中加载

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT || 3306,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  connectTimeout: 60000, // 连接超时时间增加到60秒
  acquireTimeout: 60000, // 获取连接超时
  timeout: 60000, // 查询超时
  charset: 'utf8mb4' // 设置字符集
});

// 监听连接池错误
pool.on('error', (err) => {
  console.error('数据库池错误:', err);
});

// 测试数据库连接
const testConnection = async () => {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功！');
    connection.release();
    return true;
  } catch (error) {
    console.error('数据库连接失败：', error.message);
    console.error('详细错误信息：', error);
    console.error('环境变量：', {
      DB_HOST: process.env.DB_HOST,
      DB_USER: process.env.DB_USER,
      DB_NAME: process.env.DB_NAME,
      DB_PORT: process.env.DB_PORT,
      // 注意：不输出密码
    });
    return false;
  }
};

// 初始化数据库表
const initDatabase = async () => {
  try {
    const connection = await pool.getConnection();
    
    // 创建用户表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        email VARCHAR(100) UNIQUE,
        role VARCHAR(20) DEFAULT 'user',
        access_token VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    
    console.log('数据库表初始化成功！');
    connection.release();
  } catch (error) {
    console.error('数据库初始化失败：', error.message);
  }
};

module.exports = {
  pool,
  testConnection,
  initDatabase
}; 